import React, {useState, useEffect} from 'react';
import {Form, Input, Button, Typography, Row, Col, message} from 'antd';
import {LockOutlined, UserOutlined, MailOutlined, DownCircleFilled, RightCircleFilled} from '@ant-design/icons';
import {Link, useNavigate} from 'react-router-dom';
import {register, sendVerificationCode} from "../api/loginApi";
import '../styles/RegisterPage.css';
import SelectRegion from "./SelectRegion";

const {Title} = Typography;

const RegisterPage: React.FC = () => {
    const [form] = Form.useForm();

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [company, setCompany] = useState('');
    const [rePassword, setRePassword] = useState('');
    const [fullName, setFullName] = useState('');
    const [verificationCode, setVerificationCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [region, setRegion] = useState('');
    const [step, setStep] = useState(1);

    const onFinish = async (values: any) => {
        if (password.length < 8) {
            messageApi.warning('The password length must be greater than eight characters.');
            return;
        }

        if (password !== rePassword) {
            messageApi.warning('The two passwords do not match.');
            return;
        }

        const registerForm = {
            email: email,
            username: fullName,
            password: password,
            verifyCode: verificationCode,
            region: region,
        };
        if (!region) {
            messageApi.warning("region cannot empty!")
            return
        }

        const res: any = await register(registerForm);
        if (res?.code === 200) {
            navigate("/main");
        } else {
            messageApi.warning('Register failed: ' + res['message']);
        }
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    const validatePasswordConfirmation = ({getFieldValue}: any) => ({
        validator(_: any, value: any) {
            if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
            }
            return Promise.reject(new Error('The two passwords that you entered do not match!'));
        },
    });

    const handleSendCode = async () => {
        if (!email) {
            messageApi.warning('Please input your email first!');
            return;
        }

        const param = {
            email: email,
            type: 2
        }

        const res: any = await sendVerificationCode(param);
        if (res?.code === 200) {
            messageApi.success('Verification code sent successfully!');
            setCountdown(60);
            setStep(3);
        } else {
            messageApi.warning('Failed to send verification code: ' + res['message']);
        }
    };

    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prevCountdown) => prevCountdown - 1);
            }, 1000);
        }
        return () => clearInterval(timer);
    }, [countdown]);

    const handleInputChange = (setter: React.Dispatch<React.SetStateAction<any>>, nextStep: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
        setter(e.target.value);
        if (step < nextStep) {
            setStep(nextStep);
        }
    };
    const selectChange = (values: any[]) => {
        console.log(values)
        let newVar
        if (values.length > 1) {
            newVar = values[0] + values[1] + ""
            setRegion(newVar)
        } else {
            newVar = values[0] + ""
            setRegion(newVar)
        }
        form.setFieldsValue({region: newVar}); // 将 region 值设置到表单中
        console.log('form', form.getFieldsValue)
    }

    return (
        <>
            {contextHolder}
            <div className="register-container">
                <Row justify="center" align="middle" className="register-row">
                    <Col>
                        <Form
                            name="register"
                            onFinish={onFinish}
                            onFinishFailed={onFinishFailed}
                            layout="vertical"
                            requiredMark={true}
                            className="register-form"
                        >
                            <Form.Item>
                                <Title level={2} style={{textAlign: 'center'}}>Register</Title>
                            </Form.Item>
                            <div className={`form-step ${step >= 1 ? 'visible' : ''}`}>
                                <Form.Item label="Email" name="email"
                                           rules={[{required: true, message: 'Please input your email!'}]}>
                                    <Input
                                        style={{height: '40px', borderRadius: '10px'}}
                                        onChange={handleInputChange(setEmail, 2)}
                                        placeholder="Please input email"
                                        prefix={<UserOutlined/>}
                                    />
                                </Form.Item>
                            </div>
                            <div className={`form-step ${step >= 2 ? 'visible' : ''}`}>
                                <Row gutter={8}>
                                    <Col span={16}>
                                        <Form.Item
                                            name="verificationCode"
                                            noStyle
                                            rules={[{required: true, message: 'Please input the verification code!'}]}
                                        >
                                            <Input
                                                style={{height: '40px', borderRadius: '10px'}}
                                                onChange={handleInputChange(setVerificationCode, 4)}
                                                placeholder="Input verification code"
                                                prefix={<MailOutlined/>}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={8}>
                                        <Button
                                            onClick={handleSendCode}
                                            type="primary"
                                            disabled={countdown > 0}
                                            style={{
                                                height: '38px',
                                                borderRadius: '10px',
                                                color: countdown > 0 ? 'black' : 'white',
                                                borderTopLeftRadius: '0px',
                                                borderBottomLeftRadius: '0px',
                                                marginLeft: '-10px',
                                                zIndex: 999
                                            }}
                                        >
                                            {countdown > 0 ? `Resend in ${countdown}s` : 'Send  Code'}
                                        </Button>
                                    </Col>
                                </Row>
                            </div>
                            <div className={`form-step ${step >= 4 ? 'visible' : ''}`}>
                                <Form.Item
                                    name="UserName"
                                    label="UserName"
                                    rules={[{required: true, message: 'Please input your UserName!'}]}
                                >
                                    <Input
                                        style={{height: '40px', borderRadius: '10px'}}
                                        onChange={handleInputChange(setFullName, 5)}
                                        placeholder="Input UserName"
                                        prefix={<UserOutlined/>}
                                    />
                                </Form.Item>
                            </div>
                            <div className={`form-step ${step >= 5 ? 'visible' : ''}`}>
                                <Form.Item
                                    name="password"
                                    label="Password"
                                    rules={[{required: true, message: 'Please input your password!'}]}
                                >
                                    <Input.Password
                                        style={{height: '40px', borderRadius: '10px'}}
                                        onChange={handleInputChange(setPassword, 6)}
                                        placeholder="Input password"
                                        prefix={<LockOutlined/>}
                                    />
                                </Form.Item>
                            </div>
                            <div className={`form-step ${step >= 6 ? 'visible' : ''}`}>
                                <Form.Item
                                    name="confirmPassword"
                                    label="Confirm Password"
                                    dependencies={['password']}
                                    rules={[
                                        {required: true, message: 'Please confirm your password!'},
                                        validatePasswordConfirmation,
                                    ]}
                                >
                                    <Input.Password
                                        style={{height: '40px', borderRadius: '10px'}}
                                        onChange={handleInputChange(setRePassword, 7)}
                                        placeholder="Repeat password"
                                        prefix={<LockOutlined/>}
                                    />
                                </Form.Item>
                            </div>
                            <div className={`form-step ${step >= 7 ? 'visible' : ''}`}>
                                <Form.Item
                                    name="company"
                                    label="Company"
                                >
                                    <Input
                                        style={{height: '40px', borderRadius: '10px'}}
                                        onChange={handleInputChange(setCompany, 8)}
                                        placeholder="Input company"
                                        prefix={<LockOutlined/>}
                                    />
                                </Form.Item>
                            </div>
                            <div className={`form-step ${step >= 8 ? 'visible' : ''}`}>
                                <Form.Item
                                    name="region"
                                    label="Task Region"
                                >
                                    <SelectRegion selectChange={selectChange}/>
                                </Form.Item>
                            </div>

                            <Form.Item style={{textAlign: 'center', marginTop: '20px'}}>
                                <Button icon={<RightCircleFilled/>} size="large" style={{borderRadius: '20px'}}
                                        type="primary" htmlType="submit">
                                    submit
                                </Button>
                            </Form.Item>
                            <Form.Item style={{textAlign: 'center', marginBottom: '0'}}>
                                <Link to="/login">Back to Login</Link>
                            </Form.Item>
                        </Form>
                    </Col>
                </Row>
            </div>
        </>
    );
};

export default RegisterPage;
